// 导入我们的解析函数
import { loadP5Data } from './parseP5Data';

// 定义彩票数据接口
interface LotteryData {
  issueNumber: string;
  date: string;
  numbers: number[];
  sales?: number;
  directBet: {
    count?: number;
    prize?: number;
  };
  bonusNumber?: number;
}

class LotteryService {
  // 获取彩票数据
  async fetchLotteryData(): Promise<LotteryData[]> {
    try {
      // 使用我们的解析函数加载数据
      const data = await loadP5Data();
      // 转换数据格式以匹配我们的接口
      return data.map(item => ({
        issueNumber: item.issue,
        date: item.date,
        numbers: item.numbers,
        sales: item.sales,
        directBet: {
          count: item.directBetCount,
          prize: item.directBetPrize
        },
        bonusNumber: item.bonus
      }));
    } catch (error) {
      console.error('获取彩票数据失败:', error);
      return [];
    }
  }

  // 分析彩票数据
  analyzeLotteryData(data: LotteryData[], usePermutationThree: boolean = false): {[key: string]: number} {
    const numberCount: {[key: string]: number} = {};

    data.forEach(item => {
      const numbersToAnalyze = usePermutationThree ? item.numbers.slice(0, 3) : item.numbers;
      numbersToAnalyze.forEach(num => {
        if (numberCount[num]) {
          numberCount[num]++;
        } else {
          numberCount[num] = 1;
        }
      });
    });

    // 按出现次数排序
    const sortedNumbers = Object.entries(numberCount)
      .sort((a, b) => b[1] - a[1])
      .reduce((obj, [key, value]) => {
        obj[key] = value;
        return obj;
      }, {} as {[key: string]: number});

    return sortedNumbers;
  }

  // 按位置分析数字出现频率
  analyzeNumbersByPosition(data: LotteryData[], usePermutationThree: boolean = false): {[key: string]: {[key: string]: number}} {
    // 初始化每个位置的计数器
    const maxPositions = usePermutationThree ? 3 : 5;
    const positionCounts: {[key: string]: {[key: string]: number}} = {};

    // 初始化位置计数器
    for (let i = 1; i <= maxPositions; i++) {
      positionCounts[i.toString()] = {};
    }

    // 遍历数据，统计每个位置上的数字出现次数
    data.forEach(item => {
      const numbersToAnalyze = usePermutationThree ? item.numbers.slice(0, 3) : item.numbers;
      numbersToAnalyze.forEach((num, index) => {
        // 只统计前maxPositions个位置
        if (index < maxPositions) {
          const position = (index + 1).toString();
          if (positionCounts[position][num]) {
            positionCounts[position][num]++;
          } else {
            positionCounts[position][num] = 1;
          }
        }
      });
    });

    // 对每个位置的数字按出现次数排序
    for (const position in positionCounts) {
      positionCounts[position] = Object.entries(positionCounts[position])
        .sort((a, b) => b[1] - a[1])
        .reduce((obj, [key, value]) => {
          obj[key] = value;
          return obj;
        }, {} as {[key: string]: number});
    }

    return positionCounts;
  }

  // 预测下次出现几率比较高的组合
  predictNextCombination(data: LotteryData[], usePermutationThree: boolean = false): number[] {
    // 过滤掉无效数据
    const validData = data.filter(item => {
      const requiredLength = usePermutationThree ? 3 : 5;
      // 确保numbers数组有足够元素，并且不全是0
      return item.numbers.length >= requiredLength && !item.numbers.slice(0, requiredLength).every(num => num === 0);
    });

    // 获取每个位置上出现频率最高的数字
    const positionCounts = this.analyzeNumbersByPosition(validData, usePermutationThree);
    const predictedCombination: number[] = [];
    const maxPositions = usePermutationThree ? 3 : 5;

    // 为每个位置选择出现频率最高的数字
    for (let i = 1; i <= maxPositions; i++) {
      const position = i.toString();
      // 获取该位置上出现频率最高的数字
      const topNumber = Object.keys(positionCounts[position])[0];
      if (topNumber) {
        predictedCombination.push(parseInt(topNumber));
      } else {
        // 如果没有数据，添加一个默认值
        predictedCombination.push(0);
      }
    }

    return predictedCombination;
  }

  // 生成多个可能的高几率组合
  generateHighProbabilityCombinations(data: LotteryData[], count: number = 5, usePermutationThree: boolean = false): number[][] {
    // 过滤掉无效数据
    const validData = data.filter(item => {
      const requiredLength = usePermutationThree ? 3 : 5;
      // 确保numbers数组有足够元素，并且不全是0
      return item.numbers.length >= requiredLength && !item.numbers.slice(0, requiredLength).every(num => num === 0);
    });

    const combinations: number[][] = [];
    const positionCounts = this.analyzeNumbersByPosition(validData, usePermutationThree);
    const totalDraws = validData.length;
    const maxPositions = usePermutationThree ? 3 : 5;

    // 生成指定数量的组合
    for (let i = 0; i < count; i++) {
      const combination: number[] = [];

      // 为每个位置选择一个出现频率较高的数字
      for (let j = 1; j <= maxPositions; j++) {
        const position = j.toString();
        const positionNumbers = Object.entries(positionCounts[position]);

        // 计算每个数字的概率
        const probabilities = positionNumbers.map(([num, count]) => {
          return {
            num: parseInt(num),
            probability: count / totalDraws
          };
        });

        // 基于概率权重随机选择一个数字
        const selectedNumber = this.selectByProbability(probabilities);
        combination.push(selectedNumber);
      }

      // 确保组合不重复
      if (!this.isCombinationExists(combinations, combination)) {
        combinations.push(combination);
      } else {
        // 如果组合重复，减少索引以重新生成
        i--;
      }
    }

    return combinations;
  }

  // 辅助方法：基于概率权重选择数字
  private selectByProbability(numbers: {num: number, probability: number}[]): number {
    // 计算总概率
    const totalProbability = numbers.reduce((sum, num) => sum + num.probability, 0);

    // 生成随机数
    let random = Math.random() * totalProbability;

    // 基于概率选择数字
    for (const num of numbers) {
      random -= num.probability;
      if (random <= 0) {
        return num.num;
      }
    }

    // 如果因为精度问题没有选择任何数字，返回第一个数字
    return numbers[0]?.num || 0;
  }

  // 辅助方法：检查组合是否已经存在
  private isCombinationExists(combinations: number[][], combination: number[]): boolean {
    return combinations.some(c => {
      return c.every((num, index) => num === combination[index]);
    });
  }

  // 查找历史出现频率最高的组合
  findMostFrequentCombinations(data: LotteryData[], count: number = 5, usePermutationThree: boolean = false): number[][] {
    // 过滤掉无效数据
    const validData = data.filter(item => {
      const requiredLength = usePermutationThree ? 3 : 5;
      // 确保numbers数组有足够元素，并且不全是0
      return item.numbers.length >= requiredLength && !item.numbers.slice(0, requiredLength).every(num => num === 0);
    });

    // 统计每个组合出现的次数
    const combinationCounts: {[key: string]: number} = {};

    validData.forEach(item => {
      // 将组合转换为字符串作为键
      const numbersToAnalyze = usePermutationThree ? item.numbers.slice(0, 3) : item.numbers;
      const combinationStr = numbersToAnalyze.join('');
      if (combinationCounts[combinationStr]) {
        combinationCounts[combinationStr]++;
      } else {
        combinationCounts[combinationStr] = 1;
      }
    });

    // 按出现次数排序
    const sortedCombinations = Object.entries(combinationCounts)
      .sort((a, b) => b[1] - a[1])
      .slice(0, count); // 取前count个

    // 转换回数字数组
    return sortedCombinations.map(([combinationStr]) => {
      return combinationStr.split('').map(num => parseInt(num));
    });
  }

}export default new LotteryService();